package com.vhly.tuite;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleAdapter;
import com.vhly.tuite.controller.*;
import com.vhly.tuite.database.DBHelper;
import com.vhly.tuite.database.SQLiteUtil;
import com.vhly.tuite.twclient.client.TwRequest;
import com.vhly.tuite.twclient.client.TwitterClient;
import com.vhly.tuite.twclient.client.TwitterParser;
import com.vhly.tuite.twclient.model.Status;
import org.w3c.dom.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2010-7-20
 * Time: 16:53:40
 *
 * @author vhly[FR]
 */
public class TweetListActivity extends ListActivity implements TwitterClientDelegate, PhotoDownloadDelegate {
//    private List<String> tweets;
    private List<HashMap<String, Object>> tweets;
//    private ArrayAdapter<String> adapter;
    private SimpleAdapter adapter;

    public static final int GRP_TW = 0;
    public static final int MNU_REFRESH = 0;
    public static final int MNU_SETTING = 1;
    public static final int MNU_WRITE = 2;

    private SharedPreferences preferences;

    private TwitterClient client;

    DBHelper helper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        tweets = new ArrayList<String>();
        tweets = new ArrayList<HashMap<String, Object>>();
//        tweets.add("Tweet1");
//        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put("tn", "vhly");
//        map.put("td", "2010/07/27");
//        map.put("tt", "TuiTe - Twitter Client for you.");
//        tweets.add(map);
//        adapter = new ArrayAdapter<String>(this, R.layout.tweetlist, R.id.twtext, tweets);
        adapter = new SimpleAdapter(this, tweets, R.layout.t1, new String[]{"pi","tn", "td", "tt"}, new int[]{R.id.pimg,R.id.txtname, R.id.txtdate, R.id.txttweet});
        setListAdapter(adapter);
        client = TwitterClient.getInstance();

        helper = new DBHelper(this, "tweets.db", null, 1);
        helper.putCol("tid", "TEXT");
        helper.putCol("tdate", "TEXT");
        helper.putCol("tt", "TEXT");   // text
        helper.putCol("uid", "TEXT");   // user id
        helper.putCol("uname", "TEXT");   // user name
        helper.putCol("uscname", "TEXT");   // user screen name
        helper.putCol("profile_image_url", "TEXT");   // user profile_image_url
        helper.putCol("url", "TEXT");   // user url

        SQLiteDatabase db = helper.getWritableDatabase();
        if (db != null) {
            Log.d("TweetListActivity", "DB create or Open");
            Vector<Status> sts = SQLiteUtil.queryStatuses(db, "tweets");
            if (sts != null && sts.size() > 0) {
                updateTweetList(sts);
            }
            db.close();
        } else {
            Log.e("TweetListActivity", "DB error");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.addSubMenu(GRP_TW, MNU_REFRESH, 0, R.string.refresh);
        menu.addSubMenu(GRP_TW, MNU_SETTING, 1, R.string.settings);
        menu.addSubMenu(GRP_TW, MNU_WRITE, 2, R.string.send);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case MNU_REFRESH:
                // TODO 对于后台的任务，建议使用 android.os.AsyncTask 实现
                TwitterAsyncTask task = new TwitterAsyncTask(client, this);
                TwRequest req = client.makeStatusesHomeTimeLineReq(null);
                task.execute(req);
                break;
            case MNU_SETTING:
                Intent settingIntent = new Intent(this, SettingActivity.class);
                startActivity(settingIntent);
                break;
            case MNU_WRITE:
                Intent sendIntent = new Intent(this, WriteTweetActivity.class);

                startActivity(sendIntent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 处理元素
     *
     * @param el Element XML DOM结构
     */
    public void process(Element el) {
        if (el != null) {
            String name = el.getNodeName();
            if (name.equals("statuses")) {
                Vector<Status> sts = TwitterParser.parseTweets(el);
                if (sts != null) {
                    int len = sts.size();
                    if (len > 0) {
                        updateTweetList(sts);
                        SQLiteDatabase db = helper.getWritableDatabase();
                        if (db != null) {
                            Log.d("TweetListActivity", "DB create or Open");
                            Status st;
                            for (int i = 0; i < len; i++) {
                                st = sts.elementAt(i);
                                SQLiteUtil.insertStatus(db, st);
                            }
                            db.close();
                        } else {
                            Log.e("TweetListActivity", "DB error");
                        }
                    }
                }
            }
        }
    }

    public void photoDownloadFinish() {
    }

    /**
     * update statuses to ListView
     *
     * @param statuses result
     */
    private void updateTweetList(Vector<Status> statuses) {
        if (statuses != null) {
            int len = statuses.size();
            Status st;
            HashMap<String, Object> map;
            PhotoStore ps = PhotoStore.getInstance();
            Vector<String> needLoad = new Vector<String>();
            for (int i = 0; i < len; i++) {
                st = statuses.elementAt(i);
                String pu = st.user.profile_image_url;
                Bitmap bmp = ps.getImage(pu);
                map = new HashMap<String, Object>();
                if(bmp == null){
                    needLoad.add(pu);
                    map.put("pi",R.drawable.deflogo);
                }else{
                    map.put("pi", bmp);
                }
                map.put("tn", st.user.name);
                map.put("td", st.created_at);
                map.put("tt", st.text);
                tweets.add(0, map);
            }
            // TODO this call must in mainloop, solve this
            adapter.notifyDataSetChanged();
            if(!needLoad.isEmpty()){
                PhotoAsyncTask pt = new PhotoAsyncTask();
                String[] us = new String[needLoad.size()];
                needLoad.copyInto(us);
                pt.execute(us);
            }
            needLoad.clear();
            needLoad = null;
        }
    }

}
